package com.yupi.moonBI.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

/**
 * 主题交换机类型：Topic
 */
public class TopicConsumer {
    private static final String EXCHANGE_NAME = "topic_exchange";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.88.130");
        factory.setPort(5672);
        Connection connection = factory.newConnection();
        
        Channel channel = connection.createChannel();

        //输入模式：消息：路由键
        channel.exchangeDeclare(EXCHANGE_NAME, "topic");

        /**
         * 主题交换机Topic
         *
         * 1、*：可以匹配一个单词
         * 2、#：可以匹配一个或多个单词
         *
         * 发送消息——“项目B 前端.后端”
         * 使用“#.前端.#”匹配路由键
         * 消费者接收：
         * 1、[后端B组] Received '前端.后端：项目B'
         * 2、[前端A组] Received '前端.后端：项目B'
         */

        String queueName = "fontend_queue";
        channel.queueDeclare(queueName, true, false, false, null);
        channel.queueBind(queueName, EXCHANGE_NAME, "#.前端.#");

        String queueName2 = "backend_queue";
        channel.queueDeclare(queueName2, true, false, false, null);
        channel.queueBind(queueName2, EXCHANGE_NAME, "#.后端.#");

        String queueName3 = "product_queue";
        channel.queueDeclare(queueName3, true, false, false, null);
        channel.queueBind(queueName3, EXCHANGE_NAME, "#.产品.#");

        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        DeliverCallback deliverCallback1 = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [前端A组] Received '" + delivery.getEnvelope().getRoutingKey()+"："+ message + "'");
        };
        DeliverCallback deliverCallback2 = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [后端B组] Received '" + delivery.getEnvelope().getRoutingKey()+"："+ message + "'");
        };
        DeliverCallback deliverCallback3 = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [产品C组] Received '" + delivery.getEnvelope().getRoutingKey()+"："+ message + "'");
        };
        //消息队列监听
        channel.basicConsume(queueName, true, deliverCallback1, consumerTag -> {
        });
        channel.basicConsume(queueName2, true, deliverCallback2, consumerTag -> {
        });
        channel.basicConsume(queueName3, true, deliverCallback3, consumerTag -> {
        });
    }
}
